package pers.hl.lib_global

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import com.blankj.utilcode.util.LogUtils
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator
import com.scwang.smartrefresh.layout.footer.ClassicsFooter
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.tencent.mmkv.MMKV
import pers.hl.lib_global.common.WanApp
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*


class KTApplication : WanApp() {


    companion object {
        private lateinit var app: KTApplication

        fun getInstance(): KTApplication {
            return app
        }
    }

    init {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(DefaultRefreshHeaderCreator { context, layout ->
            layout.setPrimaryColorsId(R.color.recommend, android.R.color.white) //全局设置主题颜色
            //                        header.setPrimaryColors();
            ClassicsHeader(context) //.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
        })
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout -> //指定为经典Footer，默认是 BallPulseFooter
            ClassicsFooter(context)
        }
    }

    override fun onCreate() {
        super.onCreate()
        app = this
        //👇初始化代码，数据默认存储在：
        //context.getFilesDir().getAbsolutePath() + "/mmkv"
        MMKV.initialize(this)
        LogUtils.d("本机SHA1，用于高德地图申请key用", sHA1(this))
    }

    /**
     * 获取APK当前签名文件的SHA1
     */
    fun sHA1(context: Context): String? {
        try {
            val info: PackageInfo = context.getPackageManager().getPackageInfo(
                context.getPackageName(), PackageManager.GET_SIGNATURES
            )
            val cert: ByteArray = info.signatures.get(0).toByteArray()
            val md: MessageDigest = MessageDigest.getInstance("SHA1")
            val publicKey: ByteArray = md.digest(cert)
            val hexString = StringBuffer()
            for (i in publicKey.indices) {
                val appendString =
                    Integer.toHexString(0xFF and publicKey[i].toInt())
                        .toUpperCase(Locale.US)
                if (appendString.length == 1) hexString.append("0")
                hexString.append(appendString)
                hexString.append(":")
            }
            var result: String = hexString.toString()
            return result.substring(0, result.length - 1)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return null
    }

}